<template>
  <view class="container">
    <view class="form-item">
      <text class="label">标题</text>
      <input v-model="title" placeholder="请输入标题">
    </view>

    <view class="form-item">
      <text class="label">手机品牌</text>
      <view class="uni-list-cell-db">
        <!-- 选择手机品牌 -->
        <picker @change="onBrandChange" :value="brand" :range="brands" range-key="name">
          <view class="picker-view">
            <text>{{ brands[brand]?.name || '请手机品牌' }}</text>
          </view>
        </picker>
      </view>
    </view>

    <view class="form-item">
      <text class="label">价格</text>
      <input v-model.number="price" type="number" placeholder="请输入价格">
    </view>

    <view class="form-item">
      <text class="label">新旧程度</text>
      <picker @change="onConditionChange" :value="condition" :range="conditions" range-key="name">
        <view class="picker-view">
          <text>{{ conditions[condition]?.name || "请选择手机新旧程度" }}</text>
        </view>
      </picker>
    </view>

    <view class="form-item">
      <text class="label">内存配置</text>
      <input v-model="memory" placeholder="请输入手机内存配置">
    </view>

    <view class="detailItem">
      <text class="label">详细描述</text>
      <textarea class="detailText" v-model="description" placeholder="请输入商品详细描述" maxlength="200" adjust-position="true"
        auto-height="100px" />
    </view>

    <view class="imgList">
      <uni-file-picker v-model="imgList" file-mediatype="image" mode="grid" limit="9" title="请选择图片,最多选择9张"
        @progress="progress" @success="success" @delete="delImg" @fail="fail"></uni-file-picker>
    </view>
    <view class="submit-button" @tap="submit">
      提交
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    getCurrentInstance,
    toRefs
  } from 'vue';

  let goodsId = ''
  onLoad((Option) => {
    getBrands()
    //初始值
    console.log("初始值");
    console.log(Option);
    goodsId = Option.goodsId
    if (goodsId) {
      getGoodsInfo()
    }
    console.log("加载时");
    console.log(imgList.value);

  })

  const title = ref('');
  const brand = ref(-1);
  const price = ref('');
  const condition = ref(-1);
  const memory = ref('');
  const description = ref('');
  const brands = ref([]);
  let imgList = ref([]);


  const conditions = [{
    name: '全新'
  }, {
    name: '九成新'
  }, {
    name: '八成新'
  }, {
    name: '七成新'
  }, {
    name: '六成新及以下'
  }];

  function findConditionIndexByName(name) {
    return conditions.findIndex(condition => condition.name === name);
  }

  //获取手机品牌列表
  const getBrands = async () => {
    http.request({
        url: '/category/list',
        method: 'GET'
      })
      .then(({
        data
      }) => {
        console.log("获取品牌列表:");
        console.log(data);
        brands.value = data.records.map(record => ({
          id: record.id,
          name: record.name
        }));
        console.log("品牌列表:");
        console.log(brands.value);
      })
      .catch((error) => {
        console.error('获取品牌列表失败:', error);
      });
  };

  function convertImageUrlsToFileList(imageUrls) {
    return imageUrls.map((imageUrl, index) => {
      // 分离 URL 中的文件名（包括扩展名）
      const fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);

      // 分离文件名和扩展名
      const [nameWithoutExt, extname] = fileName.split('.');

      // 构建对象
      return {
        name: `${nameWithoutExt}.${extname}`, // 使用序号作为文件名前缀，实际应用中可按需调整
        extname,
        url: imageUrl,
        // ... 其他您需要添加的属性
      };
    });
  }

  let picList = []
  //获取二手手机信息
  const getGoodsInfo = async () => {
    http.request({
        url: '/goods/getGoods',
        method: 'GET',
        data: {
          id: goodsId,
        }
      })
      .then((res) => {
        console.log("获取手机id");
        console.log(res);
        title.value = res.data.title;
        brand.value = res.data.categoryId - 1;
        price.value = res.data.price;
        picList = JSON.parse(res.data.pictureList);
        memory.value = res.data.storage;
        condition.value = findConditionIndexByName(res.data.degree)
        description.value = res.data.description;
        console.log("图片列表:");
        console.log(picList);
        console.log(typeof(picList));
        console.log("处理后图片列表");
        imgList.value = convertImageUrlsToFileList(picList)
        console.log(imgList.value);
      })
      .catch((err) => {
        console.log("获取手机id失败");
        console.log(err);
        uni.showToast({
          icon: 'error',
          title: '获取失败，请重试！'
        })
        uni.navigateBack()
      })
  }

  const onBrandChange = (event) => {
    console.log('品牌选择改变，携带值为：' + event.detail.value);
    brand.value = event.detail.value;
  };

  const onConditionChange = (event) => {
    condition.value = event.detail.value;
    console.log(conditions[condition.value].name);
  };

  const progress = (e) => {
    console.log('上传进度：', e)
  }




  const fail = (e) => {
    console.log('上传失败：', e)
    uni.toast('上传失败')
  }

  // const submit = () => {
  //   console.log('表单数据:', { title: title.value, brand: brand.value, price: price.value, condition: condition.value, memory: memory.value, description: description.value });
  //   // 实际提交逻辑
  // };
  function submit() {
    console.log('表单数据:', {
      title: title.value,
      categoryId: brand.value + 1,
      price: price.value,
      degree: conditions[condition.value].name,
      storage: memory.value,
      description: description.value,
      picture: imgList.value[0].url
    });
    console.log("55555");
    console.log(imgList.value);
    console.log(imgList.value.map(item => item.url));

    // 实际提交逻辑
    http.request({
        url: '/goods/updateGoods',
        method: 'put',
        data: {
          id:goodsId,
          title: title.value,
          categoryId: brand.value + 1,
          price: price.value,
          degree: conditions[condition.value].name,
          storage: memory.value,
          description: description.value,
          picture: imgList.value[0].url,
          pictureList:JSON.stringify(imgList.value.map(item => item.url))
        }
      }).then((res) => {
        console.log("编辑返回值");
        console.log(res);
        uni.showToast({
          title: '编辑成功',
          icon: 'success'
        });
       uni.navigateBack()
      })
      .catch((err) => {
        uni.showToast({
          title: '编辑失败',
          icon: 'error'
        });
        console.log(err);
      })
  }
</script>

<style scoped>
  .container {
    padding: 20px;
  }

  .form-item {
    margin-bottom: 15px;
    display: flex;

    border-bottom: 1px solid #ccc;
  }

  .label {
    width: 180rpx;
    text-align: left;
    align-self: center;
    font-size: 16px;

  }

  input,
  select {
    width: 70%;
    padding: 10px;
    /* border: 1px solid #ccc; */
    border-radius: 5px;
    font-size: 14px;
  }

  .detailItem {
    padding-bottom: 10px;
    margin-bottom: 10px;
    display: flex;
    border-bottom: 1px solid #ccc;
  }

  .detailText {
    width: 70%;
    padding: 10px;
    margin: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    color: #000;
    height: 200rpx;
  }

  .picker-view {
    width: 100%;
    padding: 10px;
    /* border: 1px solid #ccc; */
    border-radius: 5px;
    font-size: 14px;
    color: #000;
  }

  .submit-button {
    background-color: #007bff;
    color: #fff;
    text-align: center;
    padding: 10px 0;
    border-radius: 5px;
    cursor: pointer;
  }

  .imgList {
    margin-bottom: 30px;
  }
</style>
